package manager

import (
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/model"
	"github.com/tianjigames/fairy/util"
	"github.com/topfreegames/pitaya/component"
	"github.com/topfreegames/pitaya/logger"
	"sync"
)

type DaemonThread struct {
	component.LogicThread
	disConnectPlayerList map[string]*model.PlayerObject
	ContinueTime int
	lastTickTime         int64
	lock sync.Mutex
}

func NewDaemonThread() *DaemonThread {
	p := &DaemonThread{
		LogicThread:component.LogicThread{
			DieChan: make(chan struct{},1),
			Name: constants.DaemonThread,
		},
		ContinueTime: 20000,
	}

	p.Run = func() {
		timeInterval := int64(0)
		now := util.Now()
		if p.lastTickTime > 0 {
			timeInterval = now - timeInterval
		}
		p.lastTickTime = now

		//将退出登录超出20秒的玩家从离线列表中移除
		p.doCheckDisconnectPlayerList()

		//重置踢人定时器上一次踢人的时间
		TimeManager.Tick(now,timeInterval)

		//更新标准数据
		err := StandManager.Tick(now)
		if err != nil {
			logger.Log.Errorf("[DaemonThread] run failed,error:%s",err.Error())
		}

	}

	return p
}

func (p *DaemonThread) doCheckDisconnectPlayerList() {
	currTime := util.Now()
	if(len(p.disConnectPlayerList) > 0) {
		tmpMap := make(map[string]*model.PlayerObject,len(p.disConnectPlayerList))

		for k,v := range p.disConnectPlayerList {
			tmpMap[k] = v
		}

		for k,v := range tmpMap {
			if v == nil {
				delete(tmpMap,k)
				continue
			}

			//取消登录后 20秒后之后将玩家断开连接
			if p.ContinueTime < int(currTime - v.GetLogoutTime()){
				delete(tmpMap,k)
			}
		}

		length := len(tmpMap)
		if length > 0 {
			p.lock.Lock()
			p.disConnectPlayerList = make(map[string]*model.PlayerObject,length)
			for k,v := range tmpMap {
				p.disConnectPlayerList[k] = v
			}
			p.lock.Unlock()
		}

	}
}

/**
判断某个玩家是否等待断开连接
 */
func (p *DaemonThread) GetFromDisConnectPlayerList(sessionId string) *model.PlayerObject {
	if v,ok := p.disConnectPlayerList[sessionId];ok {
		return v
	}

	return nil
}

/**
删除并且获取断开连接的角色
 */
func (p *DaemonThread) RemoveAndGetDisConnectPlayer(sessionId string,playerId int) *model.PlayerObject {
	obj,ok := p.disConnectPlayerList[sessionId]
	if ok {
		p.lock.Lock()
		delete(p.disConnectPlayerList,sessionId)
		p.lock.Unlock()
	}

	if obj.GetId() != playerId {
		// 两次玩家 使用的角色不一样哦 , 通知sence ，给周围的玩家发消息，删除老角色
		logger.Log.Warnf("(removeAndGetDisConnectPlayer)同一账号的多个角色登陆,accountId:%d, oldPlayerId:%d, playerId:%d", obj.PlayerData.AccountId, obj.GetId(), playerId);
		//让PlayerAuth 创建新的吧
		return nil;
	}

	logger.Log.Debugf("[DaemonThread](removeAndGetDisConnectPlayer)accountId:%d, PlayerObject:%v", obj.PlayerData.AccountId, obj);
	return obj
}



